<?php

namespace App\Http\Controllers;

//use Illuminate\Http\Request;
use Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Book;
use App\Models\Bags;
use App\Models\Shudan;
use App\Models\BagsLiuyan;
use App\Models\UsersReg;
use App\Models\BooksComments; //短评
use App\Models\BooksReview; //长评
use App\Models\UsersAttrib;
use App\Models\BooksPingfen;
use App\Models\Chubaninfo; //出版社列表
use App\Models\SearchJilu;
use App\Models\mall\Ecy_users; //商城会员

use Session;
use Redirect;

class MobileController extends Controller
{

    public function index()
    {
        //书库图书列表
        
        //获得所有图书信息的数据->books数据库 按倒序
        //$books = Book::orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->paginate($pre_page);
        $books = Book::limit(9)->orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->get();

        //转让的图书的列表
        $bags = Bags::limit(6)->orderBy('add_time', 'desc')->get();
        foreach($bags as $bag)
        {
            //为了得到图书的信息
            $bag['books'] = $bag->hasOnebooks;
        }
        foreach($bags as $bag)
        {
            //为了得到用户的信息
            $bag['users'] = $bag->hasTcUsersReg;
        }

        foreach($bags as $bag)
        {
            //获得对应的出售书籍的留言数量
            $bag['liuyancount'] = BagsLiuyan::where('bagsid', $bag->id)->count();
        }

        return view('mobile/index', array(
            'books'   => $books,
            'bags'    => $bags
            ));
    }

    public function books()
    {
        //书库图书列表
        $pre_page = 24;

        //获得所有图书信息的数据->books数据库 按倒序
        //$books = Book::orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->paginate($pre_page);
        $books = Book::orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->simplePaginate($pre_page);

        return view('mobile.books', array('books'   => $books));
    }

    public function info($id)
    {
        // 得到书籍的信息
        $books = Book::find($id);

        if($books == null) {
            //如果书籍信息没有，显示404页面
            abort(404);
        }

        //浏览统计
        $books->click_count =  $books->click_count + 1;
        $books->save();

        //统计书有几个人转让
        $bagscount = Bags::where('book_id', $id)->count();

        //短书评的数量
        $bookscomments_count = BooksComments::where('book_id', $id)->orderBy('add_time', 'desc')->count();
        //显示短书评评论列表
        $bookscomments = BooksComments::where('book_id', $id)->orderBy('add_time', 'desc')->take(3)->get();
        foreach($bookscomments as $comment)
        {
            //为了得到会员名字和头像
            $comment['users'] = $comment->hasOnUsersReg;
        }

        //长书评的数量
        $booksreviews_count = BooksReview::where('book_id', $id)->orderBy('add_time', 'desc')->count();
        //显示长书评评论列表
        $booksreviews = BooksReview::where('book_id', $id)->orderBy('add_time', 'desc')->take(3)->get();
        foreach ($booksreviews as $reviewuser) {
            //得到发布长评论的会员资料
            $reviewuser['users'] = $reviewuser->hasOnUsersReg;
        }

            return view('mobile.info', array(
                'books' => $books, 
                'bagscount' => $bagscount,
                'bookscomments' => $bookscomments, 
                'booksreviews' => $booksreviews,
                'bookscomments_count' => $bookscomments_count,
                'booksreviews_count' => $booksreviews_count
                ));
    }

    public function ulist()
    {
        //最新注册的50会员列表
        $users = UsersReg::limit(50)->orderBy('reg_time', 'desc')->simplePaginate(10);
        foreach($users as $user)
        {
            //为了得到签名的信息
            $user['usersattribs'] = $user->hasOnUsersReg;
        }

        // foreach($users as $user)
        // {
        //     //为了得到签名的信息
        //     $usersattribs = UsersAttrib::where('uid', $user->uid)->first();
        //     $user['usersattribs'] = $usersattribs;
        // }
        //dd($users);

        return view('mobile.ulist', array(
            'users' => $users
            ));
    }   

    public function shopinfo($bagsid)
    {
        //转让图书的信息
        $bags = Bags::where('id', $bagsid)->get();
        foreach($bags as $bag)
        {
            //为了得到图书的信息
            $bag['books'] = $bag->hasOnebooks;
        }
        foreach($bags as $bag)
        {
            //为了得到商品用户的信息
            $bag['users'] = $bag->hasTcUsersReg;
        }

        if(count($bags) == 0){
            //如果商品信息已经不存在
            abort(404);
        }
        
        //return $bags;

        //return $bags[0]['users']->uid;
        $usersattribs = UsersAttrib::where('uid', $bags[0]['users']->uid)->first();

        //出售商品的留言列表
        $liuyans = BagsLiuyan::where('bagsid', $bagsid)->orderBy('add_time', 'desc')->get();
        foreach($liuyans as $liuyan)
        {
            //得到留言用户信息
            $liuyan['users'] = $liuyan->hasOneUsersReg;
        }
        
        //return $liuyans;
        //dd($liuyans);

        return view('mobile.shopinfo', array(
            'bags'   => $bags,
            'usersattribs' => $usersattribs,
            'liuyans' => $liuyans
            ));
    } 

    public function shop()
    {
        //书城里图书的列表
        //转让方式 -- J借阅，E交换，S出售，Z赠送，B以上均可
        $otype = request::input('otype'); 
        $pre_page = 10;
        if($otype == ''){
            //显示全部商品
            $bags = Bags::orderBy('add_time', 'desc')->simplePaginate($pre_page);
        }else{
            //显示转让方式的商品
            $bags = Bags::orderBy('add_time', 'desc')->where('otype', $otype)->OrWhere('otype', 'B')->simplePaginate($pre_page);
        }

        foreach($bags as $bag)
        {
            //为了得到图书的信息
            $bag['books'] = $bag->hasOnebooks;
        }
        foreach($bags as $bag)
        {
            //为了得到用户的信息
            $bag['users'] = $bag->hasTcUsersReg;
        }

        foreach($bags as $bag)
        {
            //获得对应的出售书籍的留言数量
            $bag['liuyancount'] = BagsLiuyan::where('bagsid', $bag->id)->count();
        }

        //return $bags;

        return view('mobile.shop', array(
            'bags'   => $bags,
            'otype'  => $otype
            ));
    }

    public function ushop($uid)
    {
        //书城里用户的书籍列表
        //转让方式 -- J借阅，E交换，S出售，Z赠送，B以上均可
        $otype = request::input('otype'); 
        $pre_page = 10;
        if($otype == ''){
            //显示全部商品
            $bags = Bags::where('uid', $uid)->orderBy('add_time', 'desc')->simplePaginate($pre_page);
        }else{
            //显示转让方式的商品
            $bags = Bags::where('uid', $uid)->orderBy('add_time', 'desc')->where('otype', $otype)->OrWhere('otype', 'B')->simplePaginate($pre_page);
        }

        //$bags = Bags::where('uid', $uid)->orderBy('add_time', 'absc')->paginate($pre_page);

        foreach($bags as $bag)
        {
            //为了得到图书的信息
            $bag['books'] = $bag->hasOnebooks;
        }
        foreach($bags as $bag)
        {
            //为了得到商品对应的用户信息
            $bag['users'] = $bag->hasTcUsersReg;
        }
        foreach($bags as $bag)
        {
            //获得对应的出售书籍的留言数量
            $bag['liuyancount'] = BagsLiuyan::where('bagsid', $bag->id)->count();
        }

        //会员信息
        $users = UsersReg::where('uid', $uid)->first();

        return view('mobile.ushop', array(
            'bags'   => $bags,
            'otype'  => $otype,
            'uid'    => $uid,
            'users'  => $users
            ));
    }

    public function shudan()
    {
        //书单列表
        $shudans = Shudan::orderBy('last_time', 'desc')->simplePaginate(10);

        foreach ($shudans as $shudan) {
             //得到会员资料
            $shudan['users'] = $shudan->hasOnUsersReg;
        }

        foreach ($shudans as $shudan) {
            $shudanlist = $shudan->shudanlist;
            $arr = explode(',', $shudanlist);

            $shudan['geshu'] = count($arr); // 统计书单里书籍的数量

            //得到书单对应的书籍信息
            $c = 0;
            for($i=0; $i<count($arr); $i++){
                if($c < 3){ //显示书单里的前三个图书
                    $books[$i] = Book::find($arr[$i]); 
                    $c = $c+1;
                }           
            }
            $shudan['shudanlists'] = $books; // 获得对应的图书信息
        }

        return view('mobile.shudan', array('shudans' => $shudans));
    }

    public function shudaninfo($id)
    {
        //书单信息页
        
        $shudans = Shudan::find($id);

        //书单不存在跳转到 404页面
        if(empty($shudans)){
            abort(404);
        }

        //记录书单浏览次数
        $shudans->click_count = $shudans->click_count + 1;
        $shudans->save();

        //显示书单内容
        $shudans = Shudan::where('id', $id)->get();
        foreach ($shudans as $shudan) {
            //得到会员资料
            $shudan['users'] = $shudan->hasOnUsersReg;
        }
        $shudanlist = $shudan->shudanlist;
        $arr = explode(',', $shudanlist); 
        //得到书单对应的书籍信息
        for($i=0; $i<count($arr); $i++){
            $books[$i] = Book::find($arr[$i]);            
        }

        $shudanlists = Shudan::limit(26)->orderBy('last_time', 'desc')->get();

        return view('mobile.shudaninfo',array(
            'shudan' => $shudan,
            'shudanlists' => $shudanlists,
            'books'   => $books
            ));
    }

    public function shuping()
    {
        //书评
        $booksreviews = BooksReview::limit(5)->orderBy('add_time', 'desc')->simplePaginate(10);

        foreach ($booksreviews as $booksreview) {
            $booksreview['books'] = $booksreview->hasOnebooks;
        }

        foreach ($booksreviews as $booksreview) {
            //得到发布长评论的会员资料
            $booksreview['users'] = $booksreview->hasOnUsersReg;
        }

        return view('mobile.shuping',array(
            'booksreviews' => $booksreviews
            ));
    }

    public function shupinginfo($id)
    {
        //显示发布的长书评
        $booksreviews = BooksReview::find($id);
        $books = Book::where('book_id', $booksreviews->book_id)->first();
        $users = UsersReg::where('uid', $booksreviews->uid)->first();
        return view('mobile.shupinginfo', array(
            'booksreviews' => $booksreviews, 
            'books' => $books, 'users' => $users
            ));
    }

    public function login()
    {
        //用户登录处理
        $username = request::input('username');
        $password = request::input('password'); 
        $uspa = UsersReg::where('email', $username)->orWhere('mobile', $username)->first();
        if($uspa != null) // 如果数据为空（用户名字不对）
        {
            $password1 = $uspa->password;
            $salt = $uspa->salt;
            $uid = $uspa->uid;
            $name = $uspa->user_name;

            // 加密后的密码,根据 salt 混淆密码
            $password = md5(md5($password) . $salt);
            if($password == $password1) {
                //////session保存用户名字变量为 name
                Session::put('name', $name); 
                //////session保存用户名的uid变量为 nameid  
                Session::put('nameid', $uid); 

                $uspa->login_count = $uspa->login_count + 1; // 记录登录次数
                $uspa->save();

                //商城同时登录状态
                // $ecy_users = Ecy_users::where('user_name', $username)->first();
                // if($ecy_users == null)
                // {
                //     //如果商城会员系统中没有这个会员，那么添加这个会员
                //     $ecy_users = new Ecy_users;
                //     $ecy_users->user_name = $username;  //用户名
                //     $ecy_users->email = $uspa->email;  //信箱
                //     $ecy_users->mobile_phone = $uspa->mobile; //手机号码
                //     $ecy_users->password = md5(request::input('password')); //密码
                //     $ecy_users->reg_time = time(); //注册时间
                //     $ecy_users->last_login = time(); //最后登录时间
                //     $ecy_users->save();
                // }
                // Session::put('user_name', $username);
                // setcookie('user_name', $username, 10);
                // Session::put('user_id', $ecy_users->user_id);
                //session_start();
                //$_SESSION['user_id'] = 7;
                
                //$_SESSION['user_name'] = $username;
                // Cookie::make('user_name', $username, 10);
                //$_COOKIE['user_name'] = $username;
                //商城同时登录状态end

                return 'ok';
            }
            else {
            return 'error';
            }
        }
        else {
            return 'error';
        }
    }

    public function search()
    {
        //搜索书

        // 记录搜索的内容        
        $search_text = request::input('search_text');
        
        if(Session::get('nameid')) {
            $uid = Session::get('nameid');
        }else {
            $uid = 0;
        }

        $search = SearchJilu::where('search_text', request::input('search_text'))->where('uid', $uid)->first();

        if($search == null) {
            if(trim($search_text) != '')
            {
                $searchjilu = new SearchJilu;
                $searchjilu->search_text = $search_text;
                $searchjilu->uid = $uid;
                $searchjilu->add_time = time();
                $searchjilu->save();
            }
        } else {
            $search->add_time = time();
            $search->save();
        }        

        //显示搜索出来的图书 每页显示的记录数
        $pre_page = 10;

        //获得所有搜索出来的图书信息的数据 按倒序
        $search_text = urldecode($search_text);
        $books = Book::where('book_name', 'like', '%'.trim($search_text).'%')
                        ->OrWhere('zuozhe', 'like', '%'.trim($search_text).'%')
                        ->OrWhere('isbn', 'like', '%'.trim($search_text).'%')
                        ->orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->simplePaginate($pre_page);

        return view('mobile.search', array(
            'books' => $books,
            'search_text' => $search_text
            ));

    }

    public function shopsearch()
    {
        //搜索书城
        //显示搜索出来的图书 每页显示的记录数
        $pre_page = 10;

        //获得所有搜索出来的图书信息的数据 按倒序
        $search_text = request::input('search_text');
        $search_text = urldecode($search_text);
        $bags = Bags::where('book_name', 'like', '%'.trim($search_text).'%')
                        ->OrWhere('zuozhe', 'like', '%'.trim($search_text).'%')
                        ->OrWhere('isbn', 'like', '%'.trim($search_text).'%')
                        ->orderBy('add_time', 'desc')->orderBy('book_id', 'desc')->simplePaginate($pre_page);

        foreach($bags as $bag)
        {
            //为了得到图书的信息
            $bag['books'] = $bag->hasOnebooks;
        }
        foreach($bags as $bag)
        {
            //为了得到用户的信息
            $bag['users'] = $bag->hasTcUsersReg;
        }

        foreach($bags as $bag)
        {
            //获得对应的出售书籍的留言数量
            $bag['liuyancount'] = BagsLiuyan::where('bagsid', $bag->id)->count();
        }


        return view('mobile.shopsearch', array(
            'bags'   => $bags,
            'search_text'  => $search_text
            ));

    }

    public function newoffer($bookid)
    {
        //闲置图书放入书包 提交页面
        $books = Book::where('book_id', $bookid)->first();        
        $uid = Session::get('nameid'); //登录
        $bags = Bags::where('book_id', $bookid)->where('uid',$uid)->first();
        if(empty($bags)){
            //为空，说明会员没有出售这本书，去添加页面
            return view('mobile.new_offer', array('books' => $books));
        }else{
            //提示已经在出售
            return '本图书已经在您的书城中出售了，请不要重复添加。';
        }
    }

    public function saveaddbags(Request $request)
    {
        //保存到书包
        $bags = new Bags;

        //获得用户的uid
        //$name = Session::get('name');
        $uid = Session::get('nameid'); 

        $bags->book_id   = request::input('book_id');
        $bags->uid       = $uid;
        $bags->book_name   = request::input('book_name');
        $bags->zuozhe   = request::input('zuozhe');
        $bags->isbn   = request::input('isbn');
        $bags->otype     = request::input('otype'); //J借阅，E交换，S出售，Z赠送，B以上均可
        $bags->scope     = request::input('scope'); //L当地(同城),R当地或异地
        $bags->condition = request::input('condition'); //新旧程度
        //$bags->price     = request::input('price'); //原价
        $bags->nowprice     = request::input('nowprice'); //售价
        $bags->num     = request::input('num'); //出售图书数量
        $bags->beizhu     = request::input('beizhu'); //备注
        $bags->add_time = time(); //获取当前时间戳

        $bags->save();
        
        //跳转到图书信息页面
        //$bookid = request::input('book_id');
        //return Redirect::to('info/'. $bookid);

        //跳转到书包列表页面
        return Redirect::to('u/'. $uid . '/bags');
    }

    public function myhome()
    {
        //个人中心
        $uid = Session::get('nameid'); //得到登录的用户的uid
        $users = UsersReg::where('uid', $uid)->first();

        $reading = BooksPingfen::where('uid', $uid)->where('read_state', 2)->count();
        $readwant = BooksPingfen::where('uid', $uid)->where('read_state', 1)->count();
        $readed = BooksPingfen::where('uid', $uid)->where('read_state', 3)->count();

        //统计转让的书籍数量
        $bagscount = Bags::where('uid', $uid)->count();

        return view('mobile.myhome',array(
            'users' => $users,            
            'reading' => $reading,
            'readwant' => $readwant,
            'readed' => $readed,
            'bagscount' => $bagscount
            ));
    }

    public function uhome($uid)
    {
        //会员主页

        if($uid == Session::get('nameid'))
        {
            //如果是登录会员
            return Redirect('mobile/myhome');
        }

        $users = UsersReg::where('uid', $uid)->first();

        //404页面
        if(empty($users)){
            abort(404);
        }

        $reading = BooksPingfen::where('uid', $uid)->where('read_state', 2)->count();
        $readwant = BooksPingfen::where('uid', $uid)->where('read_state', 1)->count();
        $readed = BooksPingfen::where('uid', $uid)->where('read_state', 3)->count();

        //统计会员全部商品数量
        $bagscount = Bags::where('uid', $uid)->count();

        return view('mobile.uhome',array(
            'users' => $users,
            'reading' => $reading,
            'readwant' => $readwant,
            'readed' => $readed,
            'bagscount' => $bagscount
            ));
    }

    public function readstate($readstate, $uid)
    {
        //正在读的书，想读的书，读过的书

        $users = UsersReg::where('uid',$uid)->first();
        //404页面
        if(empty($users)){
            abort(404);
        }

        $pre_page = 10;
        $reads = BooksPingfen::where('read_state', $readstate)->where('uid', $uid)->orderBy('add_time', 'desc')->simplePaginate($pre_page);

        foreach($reads as $read)
        {
            //为了得到图书的信息
            $read['books'] = $read->hasonebooks;
        }

        //得到会员
        $users = UsersReg::where('uid', $uid)->first();

        //dd($reads);

        return view('mobile.readstate',array(
            'reads' => $reads,
            'users' => $users,
            'readstate' => $readstate
            )); 
    }

    public function countlist($bookid)
    {
        // 会员转让一本书的列表
        $pre_page = 10;
        $bags = Bags::where('book_id', $bookid)->simplePaginate($pre_page);

        if($bags->count() == 0) {
            //显示404页面
            abort(404);
        }

        foreach($bags as $bag)
        {
            //为了得到图书的信息
            $bag['books'] = $bag->hasOnebooks;
        }
        foreach($bags as $bag)
        {
            //为了得到用户的信息
            $bag['users'] = $bag->hasTcUsersReg;
        }

        foreach($bags as $bag)
        {
            //获得对应的出售书籍的留言数量
            $bag['liuyancount'] = BagsLiuyan::where('bagsid', $bag->id)->count();
        }

        //return $bags;

        return view('mobile.countlist', array(
            'bags'   => $bags
            ));
    }

    public function saveusreg(Request $request)
    {
        //禁止注册的名字
        $name = request::input('us');
        $tmparray = explode($name,'波');
        if(count($tmparray)>1){
            return '%@#$###@#$ipzibo...';
        }
        // 禁止end

        //注册网站会员 保存
        $UsersReg = new UsersReg;
        $email = request::input('email');
        $username = request::input('us');        
        $password = request::input('password1');
        $mobile = request::input('mobile');
        $UsersReg->user_name = $username;
        $UsersReg->email = $email;
        $UsersReg->mobile = $mobile;
        $salt = $this->fetch_salt(4);
        $UsersReg->password = $this->compile_password($password, $salt);
        $UsersReg->salt = $salt;


        $UsersReg->reg_ip = $request->ip(); //注册ip
        $UsersReg->sex = 3; //性别默认保密 值=3
        //$UsersReg->reg_ip = $_SERVER['REMOTE_ADDR'];
        $UsersReg->reg_time = time();
        //1超级管理员；2前台管理员；3未验证会员；4普通会员；99游客
        $UsersReg->group_id = 3; //3未验证会员
        $UsersReg->valid_email = 0;  //0邮件未认证；1已通过邮件认证
        $UsersReg->integral = 2000;  //新用户注册默认拥有积分(金币)
        $UsersReg->invitation_available = 5; // 可以使用的邀请会员数量
        //5注册会员；6初级会员；7中级会员；8高级会员；9核心会员
        $UsersReg->reputation_group = 5; // 名誉会员组 
        $UsersReg->reg_laiyuan = 'M'; // 标识会员通过手机web(mobile)注册
    
        $UsersReg->save();   

        //session保存用户名字变量为 name
        Session::put('name', $username); 
        //session保存用户名的uid变量为 nameid 
        $users = UsersReg::where('user_name', $username)->first(); 
        Session::put('nameid', $users->uid); 

        //注册会员信息添加到商城数据库中
        $ecy_users = new Ecy_users;
        $ecy_users->user_name = $username;  //用户名
        $ecy_users->email = $email;  //信箱
        $ecy_users->mobile_phone = $mobile; //手机号码
        $ecy_users->password = md5($password); //密码
        $ecy_users->reg_time = time(); //注册时间
        $ecy_users->last_login = time(); //最后登录时间
        $ecy_users->save();

        return Redirect('mobile'); // 注册完成跳转到首页
    }
    /**
    * 生成密码种子
    */
    public function fetch_salt($length = 4)
    {
        for ($i = 0; $i < $length; $i++)
        {
            //$salt .= chr(rand(97, 122)); //不知道为什么 .= 运算符报错变量salt未定义
            $salt[$i] = chr(rand(97, 122));
        }

        $salt = $salt[0] . $salt[1] . $salt[2] . $salt[3]; //
        return $salt;
    }
    /**
    * 根据 salt 混淆密码
    */
    public function compile_password($password, $salt)
    {
        $password = md5(md5($password) . $salt);
        return $password;
    }

    public function chubanshelist()
    {
        //出版社列表
        $chubaninfos = Chubaninfo::orderBy('chuban_id', 'desc')->paginate(6);
        return view('mobile.chubanshelist',array(
            'chubaninfos' => $chubaninfos
        ));
    }

    function get_userip()
    {
        // 获得用户真实ip地址
        if($_SERVER[HTTP_X_FORWARDED_FOR]=='') 
        {
            if($_SERVER[HTTP_REMOTE_ADDR]=='') 
            {
                $userip=$_SERVER[HTTP_CLIENT_IP];  
            } 
            else 
            {
                $userip=$_SERVER[HTTP_REMOTE_ADDR];
            }
        } 
        else 
        {
            $userip=$_SERVER[HTTP_X_FORWARDED_FOR];
        }
        return $userip;
    }

}
